from selenium.webdriver.chrome.webdriver import WebDriver

from base.utils.TimeUtil import TimeUtil
from models.book import BookInfo


class IMOOC:
    def __init__(self, driver: WebDriver):
        self.driver = driver

    def sync_article(self, book_info: BookInfo):
        article_title: str = book_info.get_article_title()
        content: str = book_info.generate_markdown_article()
        tags: list = book_info.get_tag_list()
        self.driver.get('http://www.imooc.com/article/publish#')
        # 选择markdown编辑器
        self.driver.find_element_by_xpath('//span[@class="js-change-editor"][@data-type="0"]').click()
        # 写标题
        self.driver.find_element_by_xpath('//*[@id="article_title"]').send_keys(article_title)
        # 写内容
        self.driver.find_element_by_xpath('//div[@class="cledit-section"]/span[1]').send_keys(content)
        # 点击发表
        self.driver.find_element_by_xpath('//span[@class="publish-btn js-article-publish"]').click()
        # 点击随机封面
        self.driver.find_element_by_xpath('//*[@id="pic_random_btn"]').click()
        # 点击展开栏目框
        self.driver.find_element_by_xpath('//*[@id="column_name"]').click()
        # 选择栏目
        '''
        <li data-columnid="2" class="modal-li-item">职场生活</li>
        <li data-columnid="116" class="modal-li-item">区块链</li>
        <li data-columnid="117" class="modal-li-item">人工智能</li>
        <li data-columnid="118" class="modal-li-item">云计算/大数据</li>
        <li data-columnid="119" class="modal-li-item">前端开发</li>
        <li data-columnid="120" class="modal-li-item">后端开发</li>
        <li data-columnid="121" class="modal-li-item">移动开发</li>
        <li data-columnid="122" class="modal-li-item">工具资源</li>
        <li data-columnid="123" class="modal-li-item">幽默段子</li>
        <li data-columnid="124" class="modal-li-item">其它</li>
        <li data-columnid="125" class="modal-li-item">资讯</li>
        '''
        self.driver.find_element_by_xpath('//li[@class="modal-li-item"][@data-columnid="122"]').click()
        # 选择文章类型
        self.driver.find_element_by_xpath('//*[@id="original_name"]').click()
        self.driver.find_element_by_xpath('//*[@id="original_ul_list"]/li[3]').click()
        # 选择标签
        tags.append('资讯')
        tags.append('JAVA')
        tags.append('Python')
        for tag in tags[:3]:
            tag_input = self.driver.find_element_by_xpath('//*[@id="search_input"]')
            tag_input.clear()
            tag_input.send_keys(tag)
            TimeUtil.short_sleep()
            try:
                self.driver.find_element_by_xpath('//span[@class="tag-item"][@style="display: block;"][1]').click()
            except Exception as e:
                continue
            TimeUtil.short_sleep()
        # 发布
        self.driver.find_element_by_xpath('//*[@id="save_article"]').click()
        book_info.imooc = 1
        return book_info
